from enum import Enum
from config import VALUABLE_ORDER_COMBINATIONS

class UOOrder:
    """Order class for managing Bulk Order Deeds and their sub-orders"""
    
    def __init__(self, name, weight=1, quality_requirement="Normal", material_requirement="Iron Ingots", amount=0):
        """Initialize an order
        
        Args:
            name (str): Order name
            weight (int): Order weight (in Stone)
            quality_requirement (str): Item quality requirement, defaults to "Normal"
            material_requirement (str): Material requirement, defaults to "Iron Ingots"
            amount (int): Required quantity for the order
        """
        self.name = name
        self.serial = None  # Order serial number
        self.is_blessed = False  # Whether the order is blessed
        self.weight = weight
        self.size = None  # Order size: True for small, False for large
        self.quality_requirement = quality_requirement
        self.material_requirement = material_requirement
        self.amount = amount
        self.sub_orders = []  # List of sub-orders
        self.required_items = []  # List of items to craft, each item is {"name": str, "amount": int, "completed": int}
        self.type = None  # Order type: 'Recyclable', 'Valuable', 'Normal'
        self.is_completed = False  # Whether the order is completed
        
    def add_required_item(self, item_name, required_amount=0, completed_amount=0):
        """Add an item to be crafted
        
        Args:
            item_name (str): Item name
            required_amount (int): Required quantity
            completed_amount (int): Completed quantity
        """
        self.required_items.append({
            "name": item_name,
            "amount": required_amount,
            "completed": completed_amount
        })
        
    def add_sub_order(self, sub_order):
        """Add a sub-order
        
        Args:
            sub_order (Order): Sub-order object
        """
        self.sub_orders.append(sub_order)
        
    def get_total_items_needed(self):
        """Get the total number of items needed for the order (including sub-orders)
        
        Returns:
            int: Total number of items
        """
        total = self.amount
        for sub_order in self.sub_orders:
            total += sub_order.get_total_items_needed()
        return total
        
    def analyze_type(self):
        """Analyze and set the order type based on its properties.
        
        Order types and their criteria:
        
        1. Recyclable
           - Definition: Small orders used for grinding.
           - Criteria: Must be a Small Bulk Order AND the material must be one of:
             * Iron Ingots
             * Dull Copper Ingots
             * Shadow Iron Ingots
           - Action: Store in order book.
        
        2. Valuable
           - Definition: Orders that can be exchanged for rewards.
           - Criteria: Must match ALL conditions in VALUABLE_ORDER_COMBINATIONS:
             * Item name
             * Amount required
             * Quality requirement
             * Material requirement
           - Action: Store in order book.
        
        3. Normal
           - Definition: Regular orders without special value.
           - Criteria: All orders that are not Recyclable or Valuable.
           - Action: Discard.
        """
        
        # Define recyclable materials
        recyclable_materials = ["Iron Ingots", "Dull Copper Ingots", "Shadow Iron Ingots"]
        
        # Handle small orders
        if self.size == "Small":
            # 1. Check if order is Recyclable (small order with basic materials)
            if self.material_requirement in recyclable_materials:
                self.type = "Recyclable"
                return
                
            # 2. Check if order is Valuable by matching against VALUABLE_ORDER_COMBINATIONS
            for item in self.required_items:
                item_name = item['name']
                required_amount = item['amount']
                quality = self.quality_requirement
                material = self.material_requirement
                
                # Check against each valuable combination
                for combo in VALUABLE_ORDER_COMBINATIONS:
                    # Unpack the tuple values
                    combo_item, combo_amount, combo_quality, combo_material = combo
                    
                    # Check if ALL conditions match
                    if (item_name == combo_item and
                        required_amount == combo_amount and
                        quality.lower() == combo_quality.lower() and
                        material == combo_material):
                        self.type = "Valuable"
                        return
                        
            # 3. If not recyclable or valuable, it's a Normal small order
            self.type = "Normal"
            return
                
        # Handle large orders
        elif self.size == "Large":
            # Check if all items in the order match valuable combinations
            all_valuable = True
            valuable_count = 0
            
            # Get common properties for the large order
            quality = self.quality_requirement
            material = self.material_requirement
            
            # Check each item in the order
            for item in self.required_items:
                item_name = item['name']
                required_amount = item['amount']
                
                # Look for a match in VALUABLE_ORDER_COMBINATIONS
                found_match = False
                for combo in VALUABLE_ORDER_COMBINATIONS:
                    combo_item, combo_amount, combo_quality, combo_material = combo
                    
                    # Check for exact match
                    if (item_name == combo_item and
                        required_amount == combo_amount and
                        quality.lower() == combo_quality.lower() and
                        material == combo_material):
                        found_match = True
                        valuable_count += 1
                        break
                
                if not found_match:
                    all_valuable = False
            
            # If all items are valuable, the order is valuable
            if all_valuable and valuable_count == len(self.required_items):
                self.type = "Valuable"
                return
                
        # Default to normal
        self.type = "Normal"
        
    def __str__(self):
        """Return a string representation of the order
        
        Returns:
            str: String representation of the order information
        """
        order_info = f"Name: {self.name}\n"
        order_info = f"Serial: 0x{self.serial:X}\n"
        order_info += f"Blessed: {self.is_blessed}\n"
        order_info += f"Weight: {self.weight} Stone\n"
        order_info += f"Size: {self.size}\n"
        order_info += f"Quality: {self.quality_requirement}\n"
        order_info += f"Material: {self.material_requirement}\n"
        order_info += f"Type: {self.type}\n"
        
        # Display all items to be crafted
        if self.required_items:
            for item in self.required_items:
                order_info += f"Required Item: {item['name']}\n"
                order_info += f"Amount Required: {item['amount']}\n"
                order_info += f"Amount Completed: {item['completed']}\n"
        
        if self.sub_orders:
            order_info += "Sub Orders:\n"
            for sub_order in self.sub_orders:
                sub_order_str = str(sub_order).replace('\n', '\n  ')
                order_info += f"  {sub_order_str}\n"
                
        order_info += f"Completed: {self.is_completed}\n"
                
        return order_info 